package order

import (
	"context"
	"fmt"
	"go_final/mxshop_api/order_web/api"
	"go_final/mxshop_api/order_web/forms"
	"go_final/mxshop_api/order_web/global"
	"go_final/mxshop_api/order_web/models"
	orderpb "go_final/mxshop_api/order_web/proto/protofile/order"
	"net/http"
	"strconv"

	"github.com/smartwalle/alipay/v3"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	fmt.Println("开始获取订单列表")
	pages := c.DefaultQuery("psize", "0")
	pagesInt, _ := strconv.Atoi(pages)

	perNum := c.DefaultQuery("pnum", "0")
	perNumInt, _ := strconv.Atoi(perNum)

	request := orderpb.OrderFilterRequest{
		Pages:       int32(pagesInt),
		PagesPerNum: int32(perNumInt),
	}

	// 检查是不是管理员
	userID, _ := c.Get("userId")
	claims, _ := c.Get("claims")
	model := claims.(*models.CustomClaims)

	if model.AuthorityId == 1 /* 等于1是普通用户, 需要传ID */ {
		request.UserID = int32(userID.(uint))
	}

	// parentSpan, _ := c.Get("parentSpan")
	// opentracing.ContextWithSpan(context.Background(), parentSpan.(opentracing.Span))
	//res, err := global.OrderClient.OrderList(context.WithValue(context.Background(), "ginContext", c), &request)
	res, err := global.OrderClient.OrderList(c, &request)

	if err != nil {
		zap.S().Errorw("invoke 【订单服务】 失败")
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func New(c *gin.Context) {
	createOrderForm := forms.CreateOrderForm{}

	err := c.ShouldBind(&createOrderForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	userID, _ := c.Get("userId")
	claims, _ := c.Get("claims")
	fmt.Println("claims", claims)
	fmt.Println("userID", userID)

	//res, err := global.OrderClient.Create(context.Background(), &orderpb.OrderRequest{
	res, err := global.OrderClient.Create(c, &orderpb.OrderRequest{
		UserID:  int32(userID.(uint)),
		Address: createOrderForm.Address,
		Name:    createOrderForm.Name,
		Mobile:  createOrderForm.Mobile,
		Post:    createOrderForm.Post,
	})

	if err != nil {
		zap.S().Error("插入订单表失败, ", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}

	// 返回支付宝的支付URL
	alipayInfo := global.ServerConfig.AliPayInfo
	client, err := alipay.New(alipayInfo.AppID, alipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Error("实例化支付宝client失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	err = client.LoadAliPayPublicKey(alipayInfo.AliPublicKey)
	if err != nil {
		zap.S().Error("LoadAliPayPublicKey失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	fmt.Println("res.OrderSn", res.OrderSn)
	var p = alipay.TradePagePay{} // 网页支付
	p.NotifyURL = alipayInfo.NotifyURL
	p.ReturnURL = alipayInfo.ReturnURL // 支付完成以后跳转到哪个页面
	p.Subject = "FelixChan的测试订单, 编号: " + res.OrderSn
	p.OutTradeNo = res.OrderSn
	p.TotalAmount = strconv.FormatFloat(float64(res.Total), 'f', 2, 64)
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := client.TradePagePay(p)
	if err != nil {
		zap.S().Error("生成支付URL失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"id":         res.ID,
		"alipay_url": url.String(),
	})
}

func Detail(c *gin.Context) {
	orderID := c.Param("id")
	orderIDInt, err := strconv.Atoi(orderID)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "未传入订单ID",
		})
	}

	request := orderpb.OrderRequest{
		ID: int32(orderIDInt),
	}
	userID, _ := c.Get("userId")
	claims, _ := c.Get("claims")
	model := claims.(*models.CustomClaims)
	if model.AuthorityId == 1 /* 等于1是普通用户, 需要传ID */ {
		request.UserID = int32(userID.(uint))
	}

	res, err := global.OrderClient.OrderDetail(context.Background(), &request)
	if err != nil {
		zap.S().Error("invoke get OrderDetail failed")
		api.HandleGrpcError2Http(err, c)
		return
	}

	// 返回支付宝的支付URL
	alipayInfo := global.ServerConfig.AliPayInfo
	client, err := alipay.New(alipayInfo.AppID, alipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Error("实例化支付宝client失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	err = client.LoadAliPayPublicKey(alipayInfo.AliPublicKey)
	if err != nil {
		zap.S().Error("LoadAliPayPublicKey失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	var p = alipay.TradePagePay{} // 网页支付
	p.NotifyURL = alipayInfo.NotifyURL
	p.ReturnURL = alipayInfo.ReturnURL // 支付完成以后跳转到哪个页面
	p.Subject = "FelixChan的测试订单, 编号: " + res.OrderInfo.OrderSn
	p.OutTradeNo = res.OrderInfo.OrderSn
	p.TotalAmount = strconv.FormatFloat(float64(res.OrderInfo.Total), 'f', 2, 64)
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := client.TradePagePay(p)
	if err != nil {
		zap.S().Error("生成支付URL失败")
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"ali_pay_url": url.String(),
		"data":        res,
	})
}
